package user

import (
	"AI/sql/disposition"
	status "AI/util"
	"database/sql"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Setname struct {
	Account string
	NewName string
}

func SetUseName(c *gin.Context) {
	var NewName string = GetNumerSystem(c)
	if NewName == "false" {
		// c.JSON(http.StatusOK, gin.H{
		// 	"code": status.Fieldsmissing,
		// 	"body": "请输入用户名",
		// })
		return
	}
	phoneNumber, _ := c.Get("Account")
	// phone = phoneNumber
	db, err := sql.Open(disposition.Usersql["sqlname"], disposition.Usersql["sqlurl"])
	if err != nil {
		panic(err)
	}
	if err := db.Ping(); err != nil {
		fmt.Println("连接失败")
		panic(err)
	}
	// 连接数据库
	// 存入数据库
	sqls := fmt.Sprintf(`UPDATE userinfo SET username = "%s" where Account = "%s"`, NewName, phoneNumber)
	// 相同的名字由前端判断
	db.Exec(sqls)
	fmt.Println(NewName)
	if NewName == "false" {
		c.JSON(http.StatusOK, gin.H{
			"code": status.Fieldsmissing,
			"body": "失败",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": status.Success,
			"body": "修改成功",
		})
	}

	// if !NewName {

	// }
}
func GetNumerSystem(c *gin.Context) string {
	NewName, _ := c.Get("NewName")
	if len([]rune(fmt.Sprintf("%v", NewName))) <= 0 || NewName == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": status.Fieldsmissing,
			"body": "请输入正确的用户名",
		})
		return "false"
	}
	return fmt.Sprintf("%v", NewName)
}
